<template>
  <div v-if="playerState.currentSong" class="music-player">
    <div class="player-content">
      <!-- 歌曲信息 -->
      <div class="song-info">
        <img
            :alt="getSongName(playerState.currentSong)"
            :src="playerState.currentSong.coverUrl || defaultCover"
            class="current-cover"
            @error="handleImageError"
            @click="showSongDetail"
        />
        <div class="song-details">
          <div class="song-name" @click="showSongDetail">{{ getSongName(playerState.currentSong) }}</div>
          <div class="song-artist" @click="showSongDetail">{{ getArtistName(playerState.currentSong) }}</div>
        </div>
      </div>

      <!-- 播放控制 -->
      <div class="player-controls">
        <!-- 上一首 -->
        <el-icon class="control-icon" @click="prevSong">
          <Back/>
        </el-icon>

        <!-- 播放/暂停按钮 -->
        <el-icon
            :class="{ 'playing': playerState.isPlaying }"
            class="play-btn control-icon"
            @click="togglePlay"
        >
          <CaretRight v-if="!playerState.isPlaying"/>
          <Minus v-else/>
        </el-icon>

        <!-- 下一首 -->
        <el-icon class="control-icon" @click="nextSong">
          <Right/>
        </el-icon>

        <!-- 进度条 -->
        <div class="progress-bar">
          <span class="time">{{ formatTime(playerState.currentTime) }}</span>
          <el-slider
              v-model="playerState.currentTime"
              :max="playerState.duration"
              :show-tooltip="false"
              class="progress-slider"
              @change="seek"
          />
          <span class="time">{{ formatTime(playerState.duration) }}</span>
        </div>
      </div>

      <!-- 右侧控制 -->
      <div class="right-controls">
        <!-- 点赞按钮 -->
        <el-icon
            :class="{ 'liked': isLiked }"
            class="control-icon like-icon"
            @click="toggleLike"
        >
          <Star/>
        </el-icon>

        <!-- 音量控制 -->
        <div class="volume-control">
          <el-icon class="control-icon" @click="toggleMute">
            <Microphone v-if="!isMuted"/>
            <MuteNotification v-else/>
          </el-icon>
          <el-slider
              v-model="playerState.volume"
              :show-tooltip="false"
              class="volume-slider"
              @input="setVolume"
          />
        </div>

        <!-- 播放列表 -->
        <el-icon class="control-icon" @click="togglePlaylist">
          <Grid/>
        </el-icon>

        <!-- 评论 -->
        <el-icon class="control-icon" @click="showCommentModal">
          <ChatDotSquare/>
        </el-icon>
      </div>
    </div>

    <!-- 歌曲详情对话框 -->
    <el-dialog
        v-model="showSongDetailDialog"
        :close-on-click-modal="true"
        :close-on-press-escape="true"
        :title="songDetail ? getSongName(songDetail) : '歌曲详情'"
        class="song-detail-dialog"
        width="800px"
        :append-to-body="true"
        :lock-scroll="true"
        :modal="true"
    >
      <div v-if="songDetail" class="song-detail-content">
        <!-- 歌曲基本信息 -->
        <div class="song-basic-info">
          <div class="detail-cover-container">
            <el-image
                :alt="getSongName(songDetail)"
                :src="songDetail.coverUrl || defaultCover"
                class="detail-cover"
                fit="cover"
            >
              <template #error>
                <div class="image-error">
                  <el-icon>
                    <Picture/>
                  </el-icon>
                </div>
              </template>
            </el-image>
          </div>
          <div class="detail-info">
            <h2 class="detail-song-name">{{ getSongName(songDetail) }}</h2>
            <p class="detail-artist">歌手: {{ getArtistName(songDetail) }}</p>
            <p class="detail-album">专辑: {{ songDetail.album || '未知' }}</p>
            <p class="detail-duration">时长: {{ formatDuration(songDetail.duration) }}</p>
            <p class="detail-release-time">发行时间: {{ formatDate(songDetail.releaseTime) }}</p>
            <div class="detail-actions">
              <el-button
                  :icon="VideoPlay"
                  :loading="detailPlayLoading"
                  type="primary"
                  @click="playCurrentSong"
              >
                播放歌曲
              </el-button>
              <el-button
                  :icon="Star"
                  :loading="detailLikeLoading"
                  :type="songDetail.likeStatus === 1 ? 'danger' : 'default'"
                  @click="toggleSongLike"
              >
                {{ songDetail.likeStatus === 1 ? '取消喜欢' : '喜欢' }}
              </el-button>
              <el-button
                  :icon="Download"
                  :loading="detailDownloadLoading"
                  type="success"
                  @click="downloadSong"
              >
                下载
              </el-button>
            </div>
          </div>
        </div>

        <!-- 歌曲其他信息 -->
        <div class="song-additional-info">
          <el-divider content-position="left">歌曲信息</el-divider>
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">歌曲ID:</span>
              <span class="info-value">{{ songDetail.id || songDetail.songId || '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">专辑:</span>
              <span class="info-value">{{ songDetail.album || '未知' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">时长:</span>
              <span class="info-value">{{ formatDuration(songDetail.duration) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">发行时间:</span>
              <span class="info-value">{{ formatDate(songDetail.releaseTime) }}</span>
            </div>
          </div>
        </div>

        <!-- 歌词区域 -->
        <div v-if="hasLyrics" class="lyrics-section">
          <el-divider content-position="left">歌词</el-divider>
          <div class="lyrics-content">
            <pre v-if="!lyricsLoading">{{ displayedLyrics }}</pre>
            <div v-else class="lyrics-loading">
              <el-skeleton :rows="10" animated/>
            </div>
          </div>
        </div>

        <!-- 没有歌词的提示 -->
        <div v-else class="no-lyrics">
          <el-empty :image-size="100" description="暂无歌词"/>
        </div>
      </div>

      <div v-else class="loading-detail">
        <el-skeleton :rows="5" animated/>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSongDetailDialog = false">关闭</el-button>
          <el-button type="primary" @click="playCurrentSong">
            播放歌曲
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 评论对话框 -->
    <el-dialog
        v-model="showCommentDialog"
        :close-on-click-modal="true"
        :close-on-press-escape="true"
        :title="`评论 - ${getSongName(playerState.currentSong) || ''}`"
        class="comment-dialog"
        width="800px"
        :append-to-body="true"
        :lock-scroll="true"
        :modal="true"
    >
      <div class="comment-dialog-content">
        <!-- 评论列表区域 - 可滚动 -->
        <div class="comments-scrollable-area">
          <div class="comments-header">
            <h3>全部评论 ({{ commentTotal }})</h3>
          </div>

          <div
              v-if="comments.length > 0"
              v-loading="commentLoading"
              class="comments-list"
          >
            <div
                v-for="comment in comments"
                :key="comment.commentId"
                class="comment-item"
            >
              <div class="comment-avatar">
                <el-avatar :size="40" :src="comment.userAvatar || defaultAvatar">
                  {{ comment.username?.charAt(0) || 'U' }}
                </el-avatar>
              </div>
              <div class="comment-content">
                <div class="comment-header">
                  <span class="user-name">{{ comment.username || '匿名用户' }}</span>
                  <span class="comment-time">{{ formatCommentTime(comment.createTime) }}</span>
                  <!-- 当前用户标识 -->
                  <span v-if="comment.isOwn" class="own-badge">我</span>
                </div>
                <div class="comment-text">{{ comment.content }}</div>
                <div class="comment-actions">
                  <el-button
                      :icon="Star"
                      :loading="comment.liking"
                      :type="comment.liked ? 'danger' : 'default'"
                      size="small"
                      text
                      @click="toggleCommentLike(comment)"
                  >
                    {{ comment.likeCount || 0 }}
                  </el-button>

                  <!-- 删除按钮（仅显示自己的评论） -->
                  <el-button
                      v-if="comment.isOwn"
                      :icon="Delete"
                      :loading="comment.deleting"
                      size="small"
                      text
                      type="danger"
                      @click="deleteComment(comment)"
                  >
                    删除
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-else class="no-comments">
            <el-empty :image-size="100" description="暂无评论，快来发表第一条评论吧~"/>
          </div>

          <!-- 分页 - 在滚动区域内 -->
          <div v-if="commentTotal > 0" class="comment-pagination">
            <el-pagination
                v-model:current-page="commentPage.pageNum"
                v-model:page-size="commentPage.pageSize"
                :page-sizes="[5, 10, 20, 50]"
                :total="commentTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </div>
        </div>

        <!-- 发表评论 - 固定在底部 -->
        <div class="add-comment-section">
          <div class="comment-form">
            <el-input
                v-model="newComment"
                :autosize="{ minRows: 3, maxRows: 6 }"
                :maxlength="500"
                :placeholder="isLogin() ? '发表你的评论...' : '请先登录后评论'"
                :rows="3"
                show-word-limit
                type="textarea"
            />
            <div class="comment-actions">
              <el-button
                  :disabled="!newComment.trim() || !isLogin()"
                  :loading="submittingComment"
                  type="primary"
                  @click="submitComment"
              >
                发表评论
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, ref, watch} from 'vue'
import {isLogin} from '../utils/auth'
import {usePlayer} from '@/utils/player.js'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
  Back,
  CaretRight,
  ChatDotSquare,
  Delete,
  Download,
  Grid,
  Microphone,
  Minus,
  MuteNotification,
  Picture,
  Right,
  Star,
  VideoPlay
} from '@element-plus/icons-vue'
import http from "@/request/http.js"

const {
  playerState,
  togglePlay,
  nextSong,
  prevSong,
  seek,
  setVolume,
  formatTime
} = usePlayer()

// 本地状态
const isMuted = ref(false)
const previousVolume = ref(80)

// 歌曲详情相关状态
const showSongDetailDialog = ref(false)
const songDetail = ref(null)
const detailPlayLoading = ref(false)
const detailLikeLoading = ref(false)
const detailDownloadLoading = ref(false)
const lyricsLoading = ref(false)
const lyricsContent = ref('')

// 评论相关状态
const showCommentDialog = ref(false)
const comments = ref([])
const commentTotal = ref(0)
const commentLoading = ref(false)
const submittingComment = ref(false)
const newComment = ref('')

// 分页参数
const commentPage = ref({
  pageNum: 1,
  pageSize: 10
})

// 使用 Base64 内联图片作为默认封面和头像
const defaultCover = ''

const defaultAvatar = ''

// 计算是否喜欢当前歌曲
const isLiked = computed(() => {
  return playerState.currentSong?.likeStatus === 1
})

// 计算是否有歌词
const hasLyrics = computed(() => {
  if (!songDetail.value) return false

  // 检查是否已经有歌词内容
  if (lyricsContent.value && lyricsContent.value.trim().length > 0) {
    return true
  }

  // 检查多个可能的歌词字段名
  const lyrics = songDetail.value.lyrics || songDetail.value.lyric || songDetail.value.lyricContent
  return lyrics && lyrics.trim().length > 0
})

// 计算显示的歌词内容
const displayedLyrics = computed(() => {
  if (!songDetail.value) return ''

  // 优先使用从URL获取的歌词内容
  if (lyricsContent.value && lyricsContent.value.trim().length > 0) {
    return lyricsContent.value.trim()
  }

  // 然后尝试多个可能的歌词字段名
  const lyrics = songDetail.value.lyrics || songDetail.value.lyric || songDetail.value.lyricContent || ''

  // 检查是否是URL
  if (isLyricsUrl(lyrics)) {
    return '歌词加载中...'
  }

  return lyrics.trim()
})

// 判断是否是歌词URL
const isLyricsUrl = (lyrics) => {
  if (!lyrics) return false
  return lyrics.startsWith('http://') || lyrics.startsWith('https://')
}

// 获取歌曲名（兼容不同数据结构）
const getSongName = (song) => {
  if (!song) return '未知歌曲'
  return song.songName || song.name || '未知歌曲'
}

// 获取歌手名（兼容不同数据结构）
const getArtistName = (song) => {
  if (!song) return '未知歌手'
  return song.artistName || '未知歌手'
}

// 图片加载失败处理
const handleImageError = (event) => {
  event.target.src = defaultCover
}

// 显示歌曲详情
const showSongDetail = async () => {
  if (!playerState.currentSong) return
  showSongDetailDialog.value = true
  await fetchSongDetail()
}

// 获取有效的歌曲ID
const getValidSongId = () => {
  if (!playerState.currentSong) {
    console.error('当前没有播放的歌曲')
    return null
  }
  const song = playerState.currentSong
  const songId = song.id || song.songId || song.musicId
  if (!songId) {
    console.error('无法获取有效的歌曲ID，歌曲对象:', song)
    ElMessage.error('无法获取歌曲ID，请检查歌曲数据')
    return null
  }
  return songId
}

// 获取歌词内容
const fetchLyricsContent = async (lyricsUrl) => {
  if (!lyricsUrl) return ''

  try {
    console.log('📤 请求歌词内容，URL:', lyricsUrl)
    lyricsLoading.value = true

    const response = await fetch(lyricsUrl, {
      method: 'GET',
      mode: 'cors',
      cache: 'no-cache',
      headers: {
        'Accept': 'text/plain, */*',
        'Content-Type': 'text/plain; charset=utf-8'
      }
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const lyricsText = await response.text()
    console.log('✅ 直接获取歌词内容成功，长度:', lyricsText.length)
    return lyricsText
  } catch (error) {
    console.error('❌ 获取歌词内容失败:', error)
    return `获取歌词失败: ${error.message}`
  } finally {
    lyricsLoading.value = false
  }
}

// 处理歌词字段
const processLyricsField = async (songData) => {
  if (!songData) return songData

  const lyrics = songData.lyrics || songData.lyric || songData.lyricContent

  if (lyrics && isLyricsUrl(lyrics)) {
    console.log('🔗 检测到歌词URL，开始获取歌词内容')
    lyricsContent.value = await fetchLyricsContent(lyrics)
  } else if (lyrics) {
    lyricsContent.value = lyrics
  } else {
    lyricsContent.value = ''
  }

  return songData
}

// 获取歌曲详情
const fetchSongDetail = async () => {
  const songId = getValidSongId()
  if (!songId) {
    ElMessage.error('无法获取歌曲ID')
    return
  }

  try {
    console.log('📤 请求歌曲详情，歌曲ID:', songId)

    const response = await http.get(`/song/getSongDetail/${songId}`, {
      timeout: 15000,
      validateStatus: function (status) {
        return (status >= 200 && status < 300) || status === 403
      }
    })

    console.log('✅ 歌曲详情响应状态:', response.status, '数据:', response.data)

    if (response.status === 403) {
      console.warn('🔒 403错误，但尝试解析响应数据')
      if (response.data) {
        let songData = null
        if (response.data.code === 0 && response.data.data) {
          songData = processSongData(response.data.data)
        } else if (response.data.songName || response.data.name) {
          songData = processSongData(response.data)
        } else {
          songData = processSongData(response.data)
        }

        if (songData) {
          await processLyricsField(songData)
          songDetail.value = songData
          console.log('✅ 从403响应中成功解析歌曲详情数据')
          return
        }
      }
      throw new Error('403 Forbidden - 无法解析响应数据')
    }

    if (response.code === 0 && response.data) {
      const songData = processSongData(response.data)
      await processLyricsField(songData)
      songDetail.value = songData
      console.log('✅ 成功获取歌曲详情，歌词状态:', hasLyrics.value ? '有歌词' : '无歌词')
    } else {
      console.warn('❓ 歌曲详情响应数据格式不正确:', response)
      if (response.data) {
        const songData = processSongData(response.data)
        await processLyricsField(songData)
        songDetail.value = songData
        console.log('⚠️ 使用非标准格式的歌曲详情数据')
      } else {
        await useCurrentSongAsFallback()
        console.warn('使用备选歌曲数据')
      }
    }
  } catch (error) {
    console.error('❌ 获取歌曲详情失败:', error)

    if (error.response) {
      console.error('错误响应详情:', {
        status: error.response.status,
        statusText: error.response.statusText,
        data: error.response.data
      })

      if (error.response.status === 403) {
        console.warn('🔒 403错误 - 权限问题')
        await useCurrentSongAsFallback()
        ElMessage.warning('部分歌曲信息受限，已显示可用信息')
        return
      }

      if (error.response.status === 401) {
        ElMessage.error('未授权，请重新登录')
        window.dispatchEvent(new CustomEvent('showLoginModal'))
      } else if (error.response.status === 404) {
        ElMessage.warning('歌曲详情不存在')
      } else if (error.response.status === 500) {
        ElMessage.error('服务器内部错误')
      } else {
        ElMessage.error(`请求失败: ${error.response.status} ${error.response.statusText}`)
      }
    } else if (error.request) {
      console.error('网络错误，未收到响应:', error.request)
      ElMessage.error('网络错误，请检查网络连接')
    } else {
      console.error('其他错误:', error.message)
      ElMessage.error('请求失败: ' + error.message)
    }

    await useCurrentSongAsFallback()
  }
}

// 处理歌曲数据，统一歌词字段
const processSongData = (songData) => {
  if (!songData) return songData

  const processedData = {
    ...songData,
    lyrics: songData.lyric || songData.lyrics || songData.lyricContent || ''
  }

  console.log('🔧 处理后的歌曲数据 - 歌词字段:', {
    originalLyric: songData.lyric,
    originalLyrics: songData.lyrics,
    processedLyrics: processedData.lyrics
  })

  return processedData
}

// 使用当前歌曲作为备选数据
const useCurrentSongAsFallback = async () => {
  const songId = getValidSongId()
  if (!songId) {
    console.error('无法获取歌曲ID，无法创建备选数据')
    return
  }

  songDetail.value = {
    ...playerState.currentSong,
    id: songId,
    songId: songId,
    likeStatus: playerState.currentSong.likeStatus || 0,
    lyrics: playerState.currentSong.lyric || playerState.currentSong.lyrics || playerState.currentSong.lyricContent || null,
    album: playerState.currentSong.album || '未知',
    duration: playerState.currentSong.duration || 0,
    releaseTime: playerState.currentSong.releaseTime || null
  }

  console.log('🔄 使用当前歌曲作为备选数据')
  await processLyricsField(songDetail.value)
}

// 播放当前歌曲
const playCurrentSong = () => {
  if (songDetail.value) {
    const songId = songDetail.value.id || songDetail.value.songId
    const songToPlay = {
      id: songId,
      songId: songId,
      songName: songDetail.value.songName || songDetail.value.name,
      name: songDetail.value.name || songDetail.value.songName,
      artistName: songDetail.value.artistName,
      album: songDetail.value.album,
      duration: songDetail.value.duration,
      coverUrl: songDetail.value.coverUrl,
      audioUrl: songDetail.value.audioUrl,
      likeStatus: songDetail.value.likeStatus,
      lyric: songDetail.value.lyric,
      lyrics: songDetail.value.lyrics
    }

    const currentSongId = playerState.currentSong?.id || playerState.currentSong?.songId
    if (!playerState.currentSong || currentSongId !== songId) {
      const {playSong} = usePlayer()
      playSong(songToPlay)
    } else {
      if (!playerState.isPlaying) {
        togglePlay()
      }
    }

    detailPlayLoading.value = true
    setTimeout(() => {
      detailPlayLoading.value = false
    }, 500)
  }
}

// 切换歌曲喜欢状态
const toggleSongLike = async () => {
  if (!isLogin()) {
    window.dispatchEvent(new CustomEvent('showLoginModal'))
    return
  }
  if (!songDetail.value) return

  const songId = songDetail.value.id || songDetail.value.songId
  if (!songId) {
    ElMessage.error('无法获取歌曲ID')
    return
  }

  detailLikeLoading.value = true
  try {
    if (songDetail.value.likeStatus === 1) {
      const response = await http.delete(`/favorite/cancelCollectSong?songId=${songId}`)
      if (response.code === 0) {
        songDetail.value.likeStatus = 0
        ElMessage.success(`已取消喜欢: ${getSongName(songDetail.value)}`)

        const currentSongId = playerState.currentSong?.id || playerState.currentSong?.songId
        if (playerState.currentSong && currentSongId === songId) {
          playerState.currentSong.likeStatus = 0
        }

        window.dispatchEvent(new CustomEvent('favoriteUpdated', {
          detail: {
            type: 'remove',
            songId: songId,
            song: songDetail.value
          }
        }))
      } else {
        ElMessage.error(response.message || '取消喜欢失败')
      }
    } else {
      const response = await http.post(`/favorite/collectSong?songId=${songId}`)
      if (response.code === 0) {
        songDetail.value.likeStatus = 1
        ElMessage.success(`已添加到喜欢: ${getSongName(songDetail.value)}`)

        const currentSongId = playerState.currentSong?.id || playerState.currentSong?.songId
        if (playerState.currentSong && currentSongId === songId) {
          playerState.currentSong.likeStatus = 1
        }

        window.dispatchEvent(new CustomEvent('favoriteUpdated', {
          detail: {
            type: 'add',
            songId: songId,
            song: songDetail.value
          }
        }))
      } else {
        ElMessage.error(response.message || '添加喜欢失败')
      }
    }
  } catch (error) {
    console.error('喜欢操作失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    detailLikeLoading.value = false
  }
}

// 下载歌曲
const downloadSong = async () => {
  if (!songDetail.value) {
    ElMessage.error('没有可下载的歌曲信息')
    return
  }

  const song = songDetail.value
  if (!song.audioUrl) {
    ElMessage.error('该歌曲暂无下载地址')
    return
  }

  detailDownloadLoading.value = true

  try {
    console.log('开始下载歌曲:', getSongName(song))

    const link = document.createElement('a')
    link.href = song.audioUrl

    const fileName = `${getSongName(song)} - ${getArtistName(song)}.mp3`
        .replace(/[<>:"/\\|?*]/g, '_')
        .replace(/\s+/g, ' ')
        .trim()

    link.download = fileName

    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    ElMessage.success(`开始下载: ${getSongName(song)}`)

    setTimeout(() => {
      ElMessage.success(`歌曲 "${getSongName(song)}" 下载完成，已保存到下载文件夹`)
    }, 1500)

  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error(`下载失败: ${error.message}`)
  } finally {
    detailDownloadLoading.value = false
  }
}

// 格式化时长
const formatDuration = (duration) => {
  if (!duration) return '0:00'
  try {
    const seconds = typeof duration === 'string' ? parseFloat(duration) : duration
    if (isNaN(seconds)) return '0:00'
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = Math.floor(seconds % 60)
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
  } catch {
    return '0:00'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  try {
    return new Date(dateString).toLocaleDateString('zh-CN')
  } catch {
    return '未知'
  }
}

// 静音切换
const toggleMute = () => {
  if (isMuted.value) {
    playerState.volume = previousVolume.value
    setVolume(previousVolume.value)
  } else {
    previousVolume.value = playerState.volume
    playerState.volume = 0
    setVolume(0)
  }
  isMuted.value = !isMuted.value
}

// 点赞功能
const toggleLike = async () => {
  if (!isLogin()) {
    window.dispatchEvent(new CustomEvent('showLoginModal'))
    return
  }

  if (!playerState.currentSong) return

  const song = playerState.currentSong
  const songId = getValidSongId()
  if (!songId) {
    ElMessage.error('无法获取歌曲ID')
    return
  }

  try {
    if (isLiked.value) {
      const response = await http.delete(`/favorite/cancelCollectSong?songId=${songId}`)
      if (response.code === 0) {
        song.likeStatus = 0
        ElMessage.success(`已取消喜欢: ${getSongName(song)}`)

        window.dispatchEvent(new CustomEvent('favoriteUpdated', {
          detail: {
            type: 'remove',
            songId: songId,
            song: {
              id: songId,
              songId: songId,
              name: getSongName(song),
              songName: getSongName(song),
              artistName: getArtistName(song),
              album: song.album,
              duration: song.duration,
              likeStatus: 0,
              releaseTime: song.releaseTime,
              coverUrl: song.coverUrl,
              audioUrl: song.audioUrl
            }
          }
        }))
      } else {
        ElMessage.error(response.message || '取消喜欢失败')
      }
    } else {
      const response = await http.post(`/favorite/collectSong?songId=${songId}`)
      if (response.code === 0) {
        song.likeStatus = 1
        ElMessage.success(`已添加到喜欢: ${getSongName(song)}`)

        window.dispatchEvent(new CustomEvent('favoriteUpdated', {
          detail: {
            type: 'add',
            songId: songId,
            song: {
              id: songId,
              songId: songId,
              name: getSongName(song),
              songName: getSongName(song),
              artistName: getArtistName(song),
              album: song.album,
              duration: song.duration,
              likeStatus: 1,
              releaseTime: song.releaseTime,
              coverUrl: song.coverUrl,
              audioUrl: song.audioUrl
            }
          }
        }))
      } else {
        ElMessage.error(response.message || '添加喜欢失败')
      }
    }
  } catch (error) {
    console.error('喜欢操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 其他功能
const togglePlaylist = () => {
  console.log('Toggle playlist')
  window.dispatchEvent(new CustomEvent('showPlaylistModal'))
}

// 显示评论对话框
const showCommentModal = async () => {
  if (!playerState.currentSong) {
    ElMessage.warning('请先选择歌曲')
    return
  }

  showCommentDialog.value = true
  commentPage.value.pageNum = 1
  await fetchComments()
}

// 获取评论列表 - 添加调试信息
const fetchComments = async () => {
  const songId = getValidSongId()
  if (!songId) {
    ElMessage.error('无法获取歌曲ID')
    return
  }

  commentLoading.value = true
  try {
    const params = {
      pageNum: commentPage.value.pageNum,
      pageSize: commentPage.value.pageSize,
      songId: songId,
      type: 0
    }

    console.log('📤 请求评论参数:', params)
    const response = await http.post('/comment/getSongComments', params)

    if (response.code === 0 && response.data) {
      const data = response.data
      console.log('✅ 评论API响应数据:', data) // 查看原始数据

      const processedComments = (data.items || []).map(comment => {
        const isOwn = checkIfOwnComment(comment)
        console.log(`📝 评论 ${comment.commentId} 归属检查:`, {
          commentUserId: comment.userId,
          commentUserName: comment.username,
          isOwn: isOwn
        })

        return {
          ...comment,
          deleting: false,
          liking: false,
          isOwn: isOwn
        }
      })

      comments.value = processedComments
      commentTotal.value = data.total || 0

      // 统计有多少条是自己的评论
      const ownCommentsCount = processedComments.filter(comment => comment.isOwn).length
      console.log(`📊 评论统计: 总共 ${processedComments.length} 条，其中 ${ownCommentsCount} 条是自己的评论`)

    } else {
      ElMessage.error(response.message || '获取评论失败')
      comments.value = []
      commentTotal.value = 0
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败')
    comments.value = []
    commentTotal.value = 0
  } finally {
    commentLoading.value = false
  }
}

// 获取当前用户ID - 修复版本
const getCurrentUserId = () => {
  try {
    console.log('🔍 开始获取当前用户ID...')

    // 方法1: 直接从JWT Token中解析用户ID
    const token = sessionStorage.getItem('token') || localStorage.getItem('token')
    console.log('🔑 Token:', token)

    if (token) {
      try {
        // JWT Token格式: header.payload.signature
        const parts = token.split('.')
        if (parts.length === 3) {
          const payloadBase64 = parts[1]
          // 添加Base64填充（JWT使用Base64Url，可能需要处理）
          const padded = payloadBase64.padEnd(payloadBase64.length + (4 - payloadBase64.length % 4) % 4, '=')
          const payloadJson = atob(padded)
          const payload = JSON.parse(payloadJson)
          console.log('📄 Token Payload解析成功:', payload)

          // 从payload中提取用户ID - 根据您的Token结构
          if (payload.claims && payload.claims.userId) {
            const userId = payload.claims.userId
            console.log('✅ 从Token claims中获取用户ID:', userId)
            return userId
          } else if (payload.userId) {
            const userId = payload.userId
            console.log('✅ 从Token payload中获取用户ID:', userId)
            return userId
          } else {
            console.warn('⚠️ Token payload中未找到用户ID字段:', Object.keys(payload))
          }
        } else {
          console.warn('⚠️ Token格式不正确，期望3部分，实际:', parts.length)
        }
      } catch (tokenError) {
        console.warn('⚠️ Token解析失败:', tokenError)
        console.log('🔧 尝试使用decodeURIComponent解析Token...')
        try {
          // 另一种解析方式
          const payloadBase64 = token.split('.')[1]
          const payloadJson = decodeURIComponent(atob(payloadBase64).split('').map(function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
          }).join(''))
          const payload = JSON.parse(payloadJson)
          console.log('📄 Token Payload (第二种解析):', payload)

          if (payload.claims && payload.claims.userId) {
            return payload.claims.userId
          } else if (payload.userId) {
            return payload.userId
          }
        } catch (error2) {
          console.error('❌ 第二种Token解析也失败:', error2)
        }
      }
    } else {
      console.warn('❌ 未找到Token')
    }

    // 方法2: 从用户信息存储中获取
    console.log('🔄 尝试从存储中获取用户信息...')
    let userInfo = null

    // 尝试从多个位置获取用户信息
    const storageKeys = ['userInfo', 'currentUser', 'user']
    const storageTypes = [localStorage, sessionStorage]

    for (const storage of storageTypes) {
      for (const key of storageKeys) {
        try {
          const userInfoData = storage.getItem(key)
          if (userInfoData) {
            console.log(`📦 从${storage === localStorage ? 'localStorage' : 'sessionStorage'}的${key}找到数据:`, userInfoData)
            if (typeof userInfoData === 'string') {
              userInfo = JSON.parse(userInfoData)
            } else {
              userInfo = userInfoData
            }
            console.log(`✅ 从${key}解析的用户信息:`, userInfo)
            break
          }
        } catch (error) {
          console.warn(`⚠️ 从${key}获取用户信息失败:`, error)
        }
      }
      if (userInfo) break
    }

    if (userInfo) {
      // 尝试多种可能的用户ID字段名
      const userId = userInfo.id || userInfo.userId || userInfo.uid || userInfo.userID
      if (userId) {
        console.log('✅ 从用户信息中获取用户ID:', userId)
        return userId
      } else {
        console.warn('⚠️ 用户信息中未找到ID字段:', Object.keys(userInfo))
      }
    }

    // 方法3: 检查全局变量
    if (window.currentUser) {
      console.log('✅ 从window.currentUser获取用户信息:', window.currentUser)
      const userId = window.currentUser.id || window.currentUser.userId
      if (userId) {
        return userId
      }
    }

    console.warn('❌ 所有方法都无法获取用户ID')
    return null

  } catch (error) {
    console.error('❌ 获取用户ID过程中发生错误:', error)
    return null
  }
}

// 检查是否是当前用户自己的评论 - 修复版本
const checkIfOwnComment = (comment) => {
  console.log('🔍 开始检查评论归属，评论数据:', {
    commentId: comment.commentId,
    commentUserId: comment.userId,
    content: comment.content
  })

  const currentUserId = getCurrentUserId()

  // 如果没有登录，肯定不是自己的评论
  if (!currentUserId) {
    console.log('❌ 用户未登录，无法判断评论归属')
    return false
  }

  // 获取评论的用户ID
  const commentUserId = comment.userId

  if (!commentUserId) {
    console.warn('⚠️ 评论缺少userId字段:', comment)
    return false
  }

  // 转换为相同类型进行比较（避免字符串和数字比较问题）
  const currentUserIdStr = String(currentUserId)
  const commentUserIdStr = String(commentUserId)

  const isOwn = currentUserIdStr === commentUserIdStr

  console.log('🔍 评论归属检查结果:', {
    commentId: comment.commentId,
    commentContent: comment.content,
    commentUserId: commentUserId,
    commentUserIdStr: commentUserIdStr,
    currentUserId: currentUserId,
    currentUserIdStr: currentUserIdStr,
    isOwn: isOwn
  })

  return isOwn
}

// 格式化评论时间
const formatCommentTime = (timeString) => {
  if (!timeString) return ''

  try {
    const time = new Date(timeString)
    const now = new Date()
    const diff = now.getTime() - time.getTime()

    if (diff < 60000) {
      return '刚刚'
    }
    if (diff < 3600000) {
      return `${Math.floor(diff / 60000)}分钟前`
    }
    if (diff < 86400000) {
      return `${Math.floor(diff / 3600000)}小时前`
    }
    if (diff < 2592000000) {
      return `${Math.floor(diff / 86400000)}天前`
    }

    return time.toLocaleDateString('zh-CN')
  } catch {
    return timeString
  }
}

// 提交评论
const submitComment = async () => {
  if (!isLogin()) {
    window.dispatchEvent(new CustomEvent('showLoginModal'))
    return
  }

  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }

  const songId = getValidSongId()
  if (!songId) {
    ElMessage.error('无法获取歌曲ID')
    return
  }

  submittingComment.value = true
  try {
    const commentData = {
      songId: songId,
      content: newComment.value.trim()
    }

    const response = await http.post('/comment/addSongComment', commentData)
    if (response.code === 0) {
      ElMessage.success('评论发表成功')
      newComment.value = ''
      // 重新加载评论列表
      await fetchComments()
    } else {
      ElMessage.error(response.message || '评论发表失败')
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    ElMessage.error('评论发表失败')
  } finally {
    submittingComment.value = false
  }
}

// 点赞/取消点赞评论
const toggleCommentLike = async (comment) => {
  if (!isLogin()) {
    window.dispatchEvent(new CustomEvent('showLoginModal'))
    return
  }

  comment.liking = true
  try {
    if (comment.liked) {
      const response = await http.patch(`/comment/cancelLikeComment/${comment.commentId}`)
      if (response.code === 0) {
        comment.liked = false
        comment.likeCount = (comment.likeCount || 1) - 1
        ElMessage.success('取消点赞成功')
      } else {
        ElMessage.error(response.message || '取消点赞失败')
      }
    } else {
      const response = await http.patch(`/comment/likeComment/${comment.commentId}`)
      if (response.code === 0) {
        comment.liked = true
        comment.likeCount = (comment.likeCount || 0) + 1
        ElMessage.success('点赞成功')
      } else {
        ElMessage.error(response.message || '点赞失败')
      }
    }
  } catch (error) {
    console.error('点赞操作失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    comment.liking = false
  }
}

// 删除评论 - 完整实现
const deleteComment = async (comment) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
        `确定要删除这条评论吗？\n"${comment.content}"`,
        '删除确认',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'el-button--danger',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confirmButtonText = '删除中...'
              setTimeout(() => {
                done()
                setTimeout(() => {
                  instance.confirmButtonLoading = false
                }, 300)
              }, 300)
            } else {
              done()
            }
          }
        }
    )

    // 设置删除状态
    comment.deleting = true

    try {
      console.log('📤 发送删除评论请求，评论ID:', comment.commentId, '当前用户ID:', getCurrentUserId())

      // 调用删除评论API
      const response = await http.delete(`/comment/deleteSongComment/${comment.commentId}`)
      console.log('✅ 删除评论响应:', response)

      if (response.code === 0) {
        ElMessage.success('评论删除成功')

        // 从评论列表中移除该评论
        const index = comments.value.findIndex(c => c.commentId === comment.commentId)
        if (index !== -1) {
          comments.value.splice(index, 1)
          commentTotal.value = Math.max(0, commentTotal.value - 1)
        }

        // 如果当前页没有评论了且不是第一页，回到上一页
        if (comments.value.length === 0 && commentPage.value.pageNum > 1) {
          commentPage.value.pageNum -= 1
          await fetchComments()
        }
      } else {
        // 根据后端返回的错误信息显示相应提示
        if (response.message && response.message.includes('权限')) {
          ElMessage.error('您没有权限删除此评论')
        } else if (response.message && response.message.includes('未找到')) {
          ElMessage.error('评论不存在或已被删除')
        } else {
          ElMessage.error(response.message || '删除评论失败')
        }
      }
    } catch (error) {
      console.error('❌ 删除评论API调用失败:', error)

      // 详细的错误处理
      if (error.response) {
        console.error('错误响应详情:', {
          status: error.response.status,
          statusText: error.response.statusText,
          data: error.response.data
        })

        if (error.response.status === 401) {
          ElMessage.error('未授权，请重新登录')
          window.dispatchEvent(new CustomEvent('showLoginModal'))
        } else if (error.response.status === 403) {
          ElMessage.error('您没有权限删除此评论')
        } else if (error.response.status === 404) {
          ElMessage.error('评论不存在或已被删除')
        } else if (error.response.status === 500) {
          ElMessage.error('服务器内部错误，请稍后重试')
        } else {
          ElMessage.error(`删除评论失败: ${error.response.status} ${error.response.statusText}`)
        }
      } else if (error.request) {
        console.error('网络错误，未收到响应:', error.request)
        ElMessage.error('网络错误，请检查网络连接')
      } else {
        console.error('其他错误:', error.message)
        ElMessage.error('删除评论失败: ' + error.message)
      }
    }
  } catch (error) {
    // 用户取消删除
    if (error !== 'cancel') {
      console.error('删除评论确认失败:', error)
      ElMessage.error('删除评论失败')
    }
  } finally {
    // 重置删除状态
    comment.deleting = false
  }
}

// 分页大小改变
const handleSizeChange = (newSize) => {
  commentPage.value.pageSize = newSize
  commentPage.value.pageNum = 1
  fetchComments()
}

// 当前页改变
const handleCurrentChange = (newPage) => {
  commentPage.value.pageNum = newPage
  fetchComments()
}

// 监听音量变化
watch(() => playerState.volume, (newVolume) => {
  if (newVolume > 0 && isMuted.value) {
    isMuted.value = false
  }
})

// 监听对话框关闭，清理数据
watch(showSongDetailDialog, (newVal) => {
  if (!newVal) {
    setTimeout(() => {
      songDetail.value = null
      lyricsContent.value = ''
      detailDownloadLoading.value = false
    }, 300)
  }
})

// 监听评论对话框关闭
watch(showCommentDialog, (newVal) => {
  if (!newVal) {
    setTimeout(() => {
      comments.value = []
      newComment.value = ''
      commentPage.value.pageNum = 1
    }, 300)
  }
})
</script>

<style scoped>
.music-player {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-top: 1px solid #e8e8e8;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  height: 70px;
}

.player-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  padding: 0 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.song-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  min-width: 200px;
}

.current-cover {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.current-cover:hover {
  transform: scale(1.05);
}

.song-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
  cursor: pointer;
}

.song-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  line-height: 1.2;
  transition: color 0.2s ease;
}

.song-artist {
  font-size: 12px;
  color: #666;
  line-height: 1.2;
  transition: color 0.2s ease;
}

.song-name:hover,
.song-artist:hover {
  color: #409eff;
}

.player-controls {
  display: flex;
  align-items: center;
  gap: 20px;
  flex: 2;
  justify-content: center;
}

.control-icon {
  font-size: 20px;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 8px;
  border-radius: 50%;
}

.control-icon:hover {
  background-color: #f5f5f5;
  color: #409eff;
}

.play-btn {
  font-size: 24px;
  color: #409eff;
  background-color: #f0f7ff;
  padding: 12px;
}

.play-btn:hover {
  background-color: #e6f3ff;
  transform: scale(1.05);
}

.play-btn.playing {
  color: #2d8cf0;
}

.progress-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  max-width: 400px;
}

.progress-slider {
  flex: 1;
}

.time {
  font-size: 12px;
  color: #999;
  min-width: 40px;
  text-align: center;
}

.right-controls {
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
  justify-content: flex-end;
}

.volume-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.volume-slider {
  width: 80px;
}

.like-icon.liked {
  color: #ff4d4f;
  fill: #ff4d4f;
}

.like-icon:hover {
  color: #ff4d4f;
}

/* 歌曲详情对话框样式 */
.song-detail-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  position: relative;
  z-index: 2001 !important;
}

.song-detail-dialog :deep(.el-dialog__wrapper) {
  z-index: 2000 !important;
}

.song-detail-dialog :deep(.el-overlay) {
  z-index: 2000 !important;
}

.song-detail-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  margin: 0;
  padding: 20px;
  position: relative;
  z-index: 2002;
}

.song-detail-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.song-detail-dialog :deep(.el-dialog__headerbtn) {
  top: 20px;
  z-index: 2003;
}

.song-detail-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

.song-detail-content {
  max-height: 60vh;
  overflow-y: auto;
  padding: 0 10px;
  position: relative;
  z-index: 2001;
}

.song-basic-info {
  display: flex;
  gap: 24px;
  margin-bottom: 24px;
  padding: 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px;
}

.detail-cover-container {
  flex-shrink: 0;
}

.detail-cover {
  width: 150px;
  height: 150px;
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.detail-info {
  flex: 1;
}

.detail-song-name {
  font-size: 24px;
  font-weight: 700;
  color: #2c3e50;
  margin: 0 0 12px 0;
}

.detail-artist,
.detail-album,
.detail-duration,
.detail-release-time {
  font-size: 14px;
  color: #5a6c7d;
  margin: 8px 0;
  line-height: 1.4;
}

.detail-actions {
  margin-top: 20px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.song-additional-info {
  margin: 24px 0;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 12px 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.info-label {
  font-weight: 600;
  color: #495057;
}

.info-value {
  color: #6c757d;
}

.lyrics-section {
  margin: 24px 0;
}

.lyrics-content {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  max-height: 300px;
  overflow-y: auto;
}

.lyrics-content pre {
  margin: 0;
  white-space: pre-wrap;
  font-family: 'Microsoft YaHei', sans-serif;
  line-height: 1.8;
  color: #495057;
  text-align: center;
}

.lyrics-loading {
  padding: 20px;
}

.no-lyrics {
  margin: 40px 0;
}

.loading-detail {
  padding: 40px 20px;
}

.image-error {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 32px;
}

/* 评论对话框样式 */
.comment-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
  position: relative;
  z-index: 2001 !important;
}

.comment-dialog :deep(.el-dialog__wrapper) {
  z-index: 2000 !important;
}

.comment-dialog :deep(.el-overlay) {
  z-index: 2000 !important;
}

.comment-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  margin: 0;
  padding: 20px;
  position: relative;
  z-index: 2002;
}

.comment-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.comment-dialog :deep(.el-dialog__headerbtn) {
  top: 20px;
  z-index: 2003;
}

.comment-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

.comment-dialog :deep(.el-dialog__body) {
  padding: 0;
  display: flex;
  flex-direction: column;
  height: auto;
  max-height: calc(80vh - 120px);
  position: relative;
  z-index: 2001;
}

.comment-dialog-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-height: 500px;
}

.comments-scrollable-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 20px;
  min-height: 0;
}

.comments-header {
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e8e8e8;
  flex-shrink: 0;
}

.comments-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
}

.comments-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 16px;
  min-height: 0;
}

.comment-item {
  display: flex;
  gap: 12px;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.3s ease;
}

.comment-item:hover {
  background-color: #fafafa;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-avatar {
  flex-shrink: 0;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.user-name {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.comment-time {
  color: #999;
  font-size: 12px;
}

.own-badge {
  background-color: #409eff;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
}

.comment-text {
  color: #333;
  line-height: 1.5;
  margin-bottom: 8px;
  word-break: break-word;
}

.comment-actions {
  display: flex;
  gap: 16px;
}

.no-comments {
  padding: 40px 0;
  text-align: center;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.comment-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
  flex-shrink: 0;
}

.add-comment-section {
  border-top: 1px solid #e8e8e8;
  padding: 20px;
  background: #f8f9fa;
  flex-shrink: 0;
}

.comment-form {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

/* 全局对话框z-index修复 */
:deep(.el-overlay) {
  z-index: 2000 !important;
}

:deep(.el-dialog__wrapper) {
  z-index: 2000 !important;
}

:deep(.el-dialog) {
  z-index: 2001 !important;
}

/* 删除按钮样式优化 */
:deep(.el-button--danger) {
  --el-button-bg-color: #ff4d4f;
  --el-button-border-color: #ff4d4f;
}

:deep(.el-button--danger:hover) {
  --el-button-bg-color: #ff7875;
  --el-button-border-color: #ff7875;
}

/* 滚动条样式优化 */
.comments-list::-webkit-scrollbar {
  width: 6px;
}

.comments-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.comments-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.comments-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

@media (max-width: 768px) {
  .player-content {
    padding: 0 10px;
  }

  .song-info {
    min-width: 150px;
  }

  .song-name {
    font-size: 12px;
  }

  .song-artist {
    font-size: 10px;
  }

  .player-controls {
    gap: 10px;
  }

  .control-icon {
    font-size: 18px;
    padding: 6px;
  }

  .play-btn {
    font-size: 20px;
    padding: 10px;
  }

  .progress-bar {
    max-width: 200px;
  }

  .volume-slider {
    width: 60px;
  }

  .right-controls {
    gap: 10px;
  }

  .song-detail-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 20px auto;
  }

  .song-basic-info {
    flex-direction: column;
    text-align: center;
  }

  .detail-cover {
    width: 120px;
    height: 120px;
    margin: 0 auto;
  }

  .detail-actions {
    justify-content: center;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .comment-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 20px auto;
    max-height: 70vh;
  }

  .comments-scrollable-area {
    padding: 16px;
  }

  .comment-item {
    padding: 12px 0;
  }

  .comment-actions {
    flex-direction: column;
    gap: 8px;
  }

  .comment-pagination :deep(.el-pagination) {
    padding: 0;
  }

  .comment-pagination :deep(.el-pagination__sizes),
  .comment-pagination :deep(.el-pagination__jump) {
    display: none;
  }

  .add-comment-section {
    padding: 16px;
  }
}

@media (max-width: 480px) {
  .song-info {
    display: none;
  }

  .volume-control {
    display: none;
  }

  .progress-bar {
    max-width: 150px;
  }

  .detail-actions {
    flex-direction: column;
  }

  .detail-actions .el-button {
    width: 100%;
  }

  .comment-dialog :deep(.el-dialog) {
    max-height: 65vh;
  }

  .comments-scrollable-area {
    padding: 12px;
  }

  .add-comment-section {
    padding: 12px;
  }

  .comment-form {
    padding: 12px;
  }
}
</style>